package com.gg.baselibrary

import android.content.Context
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.support.v7.app.AppCompatDelegate
import android.view.inputmethod.InputMethodManager
import com.alibaba.android.arouter.launcher.ARouter
import com.gg.utils.AppManager
import com.gg.utils.AppManager.attach
import com.lsxiao.apollo.core.Apollo
import com.lsxiao.apollo.core.contract.ApolloBinder
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity


/**
 * Creator : GG
 * Time    : 2017/10/14
 * Mail    : gg.jin.yu@gmail.com
 * Explain :
 */
abstract class BaseActivity : RxAppCompatActivity() {

    private lateinit var mBinder: ApolloBinder

    private var imm: InputMethodManager? = null
//    protected var mImmersionBar: ImmersionBar? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        ARouter.getInstance().inject(this)
        initSetting()
        super.onCreate(savedInstanceState)
        setContentView(getLayoutRes())
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)

        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT

        AppManager.attach(this)

//        if (isImmersionBarEnabled())
//            initImmersionBar()


        if (useBus() && !Apollo.isBind(this))
            mBinder = Apollo.bind(this)

        initArguments()

        initTitle()

        initView()

        initData()

    }

    open fun initSetting() {

    }

    override fun onDestroy() {
        super.onDestroy()

        if (useBus() && this::mBinder.isInitialized) {
            mBinder.unbind()
        }
        this.imm = null
//        if (mImmersionBar != null)
//            mImmersionBar?.destroy()  //在BaseActivity里销毁

        AppManager.detach(this)
    }


    override fun finish() {
        super.finish()
        hideSoftKeyBoard()
    }

    fun hideSoftKeyBoard() {
        val localView = currentFocus
        if (imm == null) {
            this.imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        }
        if (localView != null && (this.imm != null)) {
            this.imm?.hideSoftInputFromWindow(localView.windowToken, 2)
        }
    }

//    open fun initImmersionBar() {
//        //在BaseActivity里初始化
//        mImmersionBar = ImmersionBar.with(this)
//        mImmersionBar?.init()
//    }


    /**
     * 是否可以使用沉浸式
     * Is immersion bar enabled boolean.
     *
     * @return the boolean
     */
//   open fun isImmersionBarEnabled(): Boolean = true

    open fun useBus(): Boolean = false


    /**
     * 获取布局id
     *
     * @return
     */
    protected abstract fun getLayoutRes(): Int


    /**
     * 获取传入数据
     */
    open fun initArguments() {

    }

    /**
     * 初始化头部
     */
    open fun initTitle(){

    }

    /**
     * 初始化View
     */
    protected abstract fun initView()

    /**
     * 初始化数据
     */
    protected abstract fun initData()

}
